package it.tukano.odt;

import it.tukano.fun.Tuple2;
import it.tukano.lang.StringExt;
import it.tukano.swingdeco.containers.JPanelExt;
import it.tukano.swingdeco.controls.JCheckBoxExt;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;

public class OdtCheckEditor extends OdtFieldEditor {

    /* default serial version uid*/
    private static final long serialVersionUID = 0;
    private final JCheckBoxExt field;
    private final boolean defaultValue;

    public OdtCheckEditor(String label) {
        this(label, new StringExt("false"));
    }

    public OdtCheckEditor(String label, StringExt defaultValue) {
        this.defaultValue = defaultValue.toBoolean(false);
        setBorder(BorderFactory.createTitledBorder(label));
        this.field = new JCheckBoxExt(label == null ? "" : label);
        add(new JPanelExt(new GridLayout(1, 1)).append(field));
    }

    @Override
    public void setValue(StringExt t) {
        field.setSelected(t.toBoolean(false));
    }

    @Override
    public Tuple2<StringExt, String> applyEditorValue(OdtField odtField, String xml) {
        StringExt s = field.isSelected() ? new StringExt("true") :  new StringExt("false");
        return Tuple2.newInstance(s, xml);
    }

    @Override
    public void clearValue() {
        field.setSelected(defaultValue);
    }

    @Override
    public void onValueChange(final Runnable task) {
        field.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                task.run();
            }
        });
    }
}
